<?php
/**
 * 支付回调地址
 *
 * @author comfiger<liuqiang@wisdudu.com>
 * @version v1.0.0
 *
 **/
namespace Xijie\Controller;
use Think\Controller;

class PayController extends Controller {
	/**
	 * 微信支付返回
	 **/
	public function weixin(){
		$string = file_get_contents("php://input");
		$file_get_contents = (array)simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
		$result_code = $file_get_contents['result_code'];
		if($result_code == 'SUCCESS' && $file_get_contents['return_code'] == 'SUCCESS'){
			$out_trade_no = $file_get_contents['out_trade_no'];
			//获取订单详情
			$orderInfo = D('Paylog')->getOrderInfoByOrderSn($out_trade_no);
			if($orderInfo['status'] == 0){
				if($orderInfo['goback_log_id']){
					//修改状态
					$gobackInfo = D('Gobacklog')->getGobackLogInfoById($orderInfo['goback_log_id']);
					if(!empty($gobackInfo['alipay']) && $gobackInfo['alipay'] > 0){
						if($gobackInfo['status'] == 0){
							$status = 3; //微信已支付
						}else if($gobackInfo['status'] == 2){
							$status = 1;
						}else if($gobackInfo['status'] == 3){
							$status = 3;
						}else{
							$status = 1;
						}
					}else{
						$status = 1;
					}
					//修改日志状态
					D('Gobacklog')->editGobackLogStatusById($orderInfo['goback_log_id'], array(
						'status' => $status,
						'weixin_ordersn' => $file_get_contents['transaction_id']
					));
					$type_id = 8;
				}else{
					$type_id = 4;
					//获取用户数据
					$userinfo = D('Member')->getMemberInfoById($orderInfo['userid']);
					//新增GoBackLog数据
					if(is_array($userinfo) && count($userinfo)){
						$go_data = array(
							'typeid' => 4,
							'contract' => $userinfo['contract'],
							'userid' => $orderInfo['userid'],
							'nickname' => $userinfo['member_nick'],
							'roomnumber' => $userinfo['room_number'],
							'card_deposit' => $file_get_contents['total_fee']/100,
							'acount' => $file_get_contents['total_fee']/100,
							'pay_type' => 2,
							'pay_card' => $file_get_contents['openid'],
							'createtime' => time(),
							'remark' => '房卡押金',
							'status' => 1,
							'weixin' => $file_get_contents['total_fee']/100,
							'weixin_ordersn' => $file_get_contents['transaction_id']
						);
						
						$row = D('Gobacklog')->addGobacklogInfo($go_data);
					}
				}
				//修改账单状态
				if($type_id == 8 && $status == 1){
					//修改押金
					if($gobackInfo['deposit']){
						D('Member')->editMemberInfo($gobackInfo['userid'], array('deposit' => $gobackInfo['deposit']));
					}
					//修改有效时间
					if($gobackInfo['rent'] > 0){
						D('Member')->editMemberRentTimeAndPtime(array(
							'member_id' => $gobackInfo['userid'],
							'leaving_time' => array('elt', strtotime($gobackInfo['end_time']))
						), array(
							'checkin_time' => strtotime($gobackInfo['begin_time']),
							'leaving_time' => strtotime($gobackInfo['end_time'])
						));
						//修改状态
						D('Costlog')->editCostLogInfo(array(
							'order_type' => 1,
							'roomnumber' => $gobackInfo['roomnumber'],
							'month' => array('lt', date('Y-m', strtotime($gobackInfo['end_time'])))
						), array(
							'status' => 1
						));
					}
					//修改物业有效时间
					if($gobackInfo['property'] > 0){
						D('Member')->editMemberRentTimeAndPtime(array(
							'member_id' => $gobackInfo['userid'],
							'property_time' => array('elt', strtotime($gobackInfo['property_time']))
						), array(
							'property_time' => strtotime($gobackInfo['property_time'])
						));

						D('Costlog')->editCostLogInfo(array(
							'order_type' => 1,
							'roomnumber' => $gobackInfo['roomnumber'],
							'month' => array('lt', date('Y-m', strtotime($gobackInfo['property_time'])))
						), array(
							'status' => 1
						));
					}
					//判断是否存在水电 electric
					if($gobackInfo['water_power'] > 0 || $gobackInfo['electric'] > 0){
						D('Costlog')->editCostLogInfo(array(
							'order_type' => 2,
							'roomnumber' => $gobackInfo['roomnumber'],
							'month' => $gobackInfo['lmonths']
						), array(
							'status' => 1
						));
						
						if(!empty($gobackInfo['orderid'])){
							D('Costlog')->editCostLogInfo(array(
								'order_type' => 2,
								'order_id' => array('in', $gobackInfo['orderid']),
							), array(
								'status' => 1
							));
						}
					}
				}
				//修改订单状态
				$row = D('Paylog')->editOrderInfoByOrderSn($out_trade_no, 1, 2);
				//添加日志
				$count = D('Paylog')->getPayLogInfoByOrderSn($out_trade_no);
				if($count == 0){
					$logdata = array(
						'order_sn' => $out_trade_no,
						'o_order_sn' => $out_trade_no,
						'pay_type' => 2,
						'openid' => $file_get_contents['openid'],
						'type_id' => $type_id,
						'point' => $file_get_contents['total_fee']/100,
						'paytime' => strtotime($file_get_contents['time_end'])
					);
					
					D('Paylog')->addPayLogInfo($logdata);
					$data = array('return_code' => '<![CDATA[SUCCESS]]>', 'return_msg' => '<![CDATA[OK]]>');
				}else{
					//writeLog('-- count -- is: '. $count);
				}
			}
		}else{
			$data = array('return_code' => '<![CDATA[FAIL]]>', 'return_msg' => '<![CDATA[OK]]>');
		}
		
		$this->response($data, 'json');
	}
	
	/**
	 * 支付宝回调
	 **/
	public function alipay(){
		$string = file_get_contents("php://input");
		//开始获取支付宝返回数据
		$discount = I('post.discount'); //折扣价
		$trade_no = I('post.trade_no'); //支付宝交易号
		$buyer_id = I('post.buyer_id'); //买家ID
		$buyer_email = I('post.buyer_email'); //买家支付账号
		$out_trade_no = I('post.out_trade_no'); //订单号
		$seller_id = I('post.seller_id'); //卖家账号ID
		$seller_email = I('post.seller_email'); //卖家账号
		$total_fee = I('post.invoice_amount'); //支付金额
		$gmt_payment = urldecode(I('gmt_payment')); //支付时间
		$trade_status = I('post.trade_status'); //订单状态 TRADE_SUCCESS 支付成功 WAIT_BUYER_PAY 创建订单成功
		$notify_id = I('post.notify_id'); //通知校验ID
		//验证订单是否正确
		if(D('Alipay')->checkAlipayNotifyId($notify_id)){
			if($trade_status == 'TRADE_SUCCESS'){
				//获取订单详情
				$orderInfo = D('Paylog')->getOrderInfoByOrderSn($out_trade_no);
				if($orderInfo['status'] == 0){
					if($orderInfo['goback_log_id']){
						//修改状态
						$gobackInfo = D('Gobacklog')->getGobackLogInfoById($orderInfo['goback_log_id']);
						if(!empty($gobackInfo['weixin']) && $gobackInfo['weixin'] > 0){
							if($gobackInfo['status'] == 0){
								$status = 2; //支付宝已支付
							}else if($gobackInfo['status'] == 3){
								$status = 1;
							}else if($gobackInfo['status'] == 2){
								$status = 2;
							}else{
								$status = 1;
							}
						}else{
							$status = 1;
						}
						
						//修改记录状态
						D('Gobacklog')->editGobackLogStatusById($orderInfo['goback_log_id'], array(
							'status' => $status,
							'alipay_ordersn' => $trade_no
						));
						$type_id = 8;
					}else{
						$type_id = 4;
						//获取用户数据
						$userinfo = D('Member')->getMemberInfoById($orderInfo['userid']);
						//新增GoBackLog数据
						if(is_array($userinfo) && count($userinfo)){
							$go_data = array(
								'typeid' => 4,
								'contract' => $userinfo['contract'],
								'userid' => $orderInfo['userid'],
								'nickname' => $userinfo['member_nick'],
								'roomnumber' => $userinfo['room_number'],
								'card_deposit' => $total_fee,
								'acount' => $total_fee,
								'pay_type' => 1,
								'pay_card' => $buyer_email,
								'createtime' => time(),
								'remark' => '房卡押金',
								'status' => 1,
								'alipay' => $total_fee,
								'alipay_ordersn' => $trade_no
							);
							
							$row = D('Gobacklog')->addGobacklogInfo($go_data);
						}
					}
					//修改账单状态
					if($type_id == 8 && $status == 1){
						//修改押金
						if($gobackInfo['deposit']){
							D('Member')->editMemberInfo($gobackInfo['userid'], array('deposit' => $gobackInfo['deposit']));
						}
						
						//修改有效时间
						if($gobackInfo['rent'] > 0){
							D('Member')->editMemberRentTimeAndPtime(array(
								'member_id' => $gobackInfo['userid'],
								'leaving_time' => array('elt', strtotime($gobackInfo['end_time']))
							), array(
								'checkin_time' => strtotime($gobackInfo['begin_time']),
								'leaving_time' => strtotime($gobackInfo['end_time'])
							));
							//修改状态
							D('Costlog')->editCostLogInfo(array(
								'order_type' => 1,
								'roomnumber' => $gobackInfo['roomnumber'],
								'month' => array('lt', date('Y-m', strtotime($gobackInfo['end_time'])))
							), array(
								'status' => 1
							));
						}
						//修改物业有效时间
						if($gobackInfo['property'] > 0){
							D('Member')->editMemberRentTimeAndPtime(array(
								'member_id' => $gobackInfo['userid'],
								'property_time' => array('elt', strtotime($gobackInfo['property_time']))
							), array(
								'property_time' => strtotime($gobackInfo['property_time'])
							));

							D('Costlog')->editCostLogInfo(array(
								'order_type' => 1,
								'roomnumber' => $gobackInfo['roomnumber'],
								'month' => array('lt', date('Y-m', strtotime($gobackInfo['property_time'])))
							), array(
								'status' => 1
							));
						}
						//判断是否存在水电 electric
						if($gobackInfo['water_power'] > 0 || $gobackInfo['electric'] > 0){
							D('Costlog')->editCostLogInfo(array(
								'order_type' => 2,
								'roomnumber' => $gobackInfo['roomnumber'],
								'month' => $gobackInfo['lmonths']
							), array(
								'status' => 1
							));
							
							if(!empty($gobackInfo['orderid'])){
								D('Costlog')->editCostLogInfo(array(
									'order_type' => 2,
									'order_id' => array('in', $gobackInfo['orderid']),
								), array(
									'status' => 1
								));
							}
						}
					}
					//修改订单状态
					$row = D('Paylog')->editOrderInfoByOrderSn($out_trade_no, 1, 1);
					//添加日志
					$count = D('Paylog')->getPayLogInfoByOrderSn($out_trade_no);
					if($count == 0){
						$logdata = array(
							'order_sn' => $out_trade_no,
							'o_order_sn' => $out_trade_no,
							'pay_type' => 1,
							'openid' => $buyer_id,
							'type_id' => $type_id,
							'point' => $total_fee,
							'paytime' => strtotime($gmt_payment)
						);
						D('Paylog')->addPayLogInfo($logdata);
					}
				}
			}
			echo 1;
		}else{
			echo 0;
		}
	}
	
	/**
	 * 创建订单
	 *
	 **/
	public function createOrder(){
		$type = I('get.type') ? trim(I('get.type')) : 'weixin';
		$ordersn = I('get.order') ? trim(I('order')) : '';
		$userid = I('get.userid') ? (int)I('get.userid') : 0;
		$ordersn = 'DC_'. $ordersn;
		//jine
		$total_fee = 100;
		$order_count = D('Paylog')->getOrderCountBySn($ordersn);
		if($order_count == 0){
			//添加订单日志
			D('Paylog')->addOrderInfo(array(
				'order_sn' => $ordersn,
				'point' => $total_fee,
				'desc' => '房卡押金',
				'pay_id' => 0,
				'createtime' => time(),
				'userid' => $userid
			));
		}
		
		switch($type){
			case 'weixin':
				$httpContent = D('WeiXin')->weixinPayString('房卡押金', $ordersn, $total_fee*100);
				
				$file_get_contents = (array)simplexml_load_string($httpContent, 'SimpleXMLElement', LIBXML_NOCDATA); //xml对象
				if($file_get_contents['return_code'] == 'SUCCESS' && $file_get_contents['result_code'] == 'SUCCESS'){
					//er wei ma dizhi
					$codeurl = $file_get_contents['code_url'];
					
					Vendor('phpqrcode.phpqrcode');
					$errorCorrectionLevel =3;//容错级别 
					$matrixPointSize = 4;//生成图片大小 
					$object = new \QRcode();
					ob_end_clean();
					$object->png($codeurl, false, $errorCorrectionLevel, $matrixPointSize, 2);
				}
			break;
			case 'alipay':
				$array = array(
					"out_trade_no" => $ordersn,
					"total_amount" => $total_fee,
					"subject"      => "房卡押金",
					"body"         => "房卡押金"
				);
				
				$result = D('Alipay')->createAction($array);
				if($result['code'] = 10000){
					Vendor('phpqrcode.phpqrcode');
					$errorCorrectionLevel =3;//容错级别 
					$matrixPointSize = 4;//生成图片大小 
					$object = new \QRcode();
					ob_end_clean();
					$object->png($result['qr_code'], false, $errorCorrectionLevel, $matrixPointSize, 2);
				}
			break;
		}
	}
		
	/** 
	 * google api 二维码生成【QRcode可以存储最多4296个字母数字类型的任意文本，具体可以查看二维码数据格式】 
	 * @param string $chl 二维码包含的信息，可以是数字、字符、二进制信息、汉字。 不能混合数据类型，数据必须经过UTF-8 URL-encoded 
	 * @param int $widhtHeight 生成二维码的尺寸设置 
	 * @param string $EC_level 可选纠错级别，QR码支持四个等级纠错，用来恢复丢失的、读错的、模糊的、数据。 
	 * L-默认：可以识别已损失的7%的数据 
	 * M-可以识别已损失15%的数据 
	 * Q-可以识别已损失25%的数据 
	 * H-可以识别已损失30%的数据 
	 * @param int $margin 生成的二维码离图片边框的距离 
	 */ 
	private function generateQRfromGoogle($chl,$widhtHeight ='150',$EC_level='L',$margin='0'){ 
		$erCodeUrl = 'http://qr.liantu.com/api.php?text='. $chl . '%26m=' .$widhtHeight;
		return $erCodeUrl;
	}
	
	public function test(){
		
		$string = '{"typeid":4,"contract":"MMGY2017051501","userid":95,"nickname":"\u5c0f\u5ddd","roomnumber":null,"card_deposit":0.01,"acount":0.01,"pay_type":2,"pay_card":"oABqjs7UHxYpT1bPsMJxqDTPUTVk","createtime":1498640785,"remark":"\u623f\u5361\u62bc\u91d1","status":1,"weixin":0.01,"weixin_ordersn":"4001252001201706287834422959"}';
		$array = json_decode($string, true);
		
		print("<pre>");
		print_r($array);
		
		//$row = D('Paylog')->addPayLogInfo($array);
		$row = D('Gobacklog')->addGobacklogInfo($array);
		echo $row;
	}
}


   